package mbsl.ui;

import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Display;

/**
 * A java-generated version of the Smooth V2 texture.
 * <p>
 * I don't know who its original creator is, but I thank her for making such a beautiful texture, and apologise for nicking her work.
 */
public class SmoothV2 {
	/**
	 * The brightness of the texture, where 255 is the brightest (white) and 0 is the darkest (black).
	 * <p>
 	 * The shade colour of each row of pixels will be set to {@code (b, b, b, a * m)} 
	 * where {@code b} is the brightness (this), {@code a} is the alpha value, and {@code m} is the modifier.
	 */
	private static final int BRIGHTNESS = 180;
	/**
	 * The modifier with which the shading values will be multiplied.  This can be viewed as the contrast.
	 * <p>
 	 * The shade colour of each row of pixels will be set to {@code (b, b, b, a * m)} 
	 * where {@code b} is the brightness, {@code a} is the alpha value, and {@code m} is the modifier (this).
	 * <p>
	 * A lower value here will increase the amount of colour shining through the texture.
	 */
	private static final double MODIFIER = 0.1;
	/**
	 * The alpha values for each row of the texture.
	 * <p>
 	 * The shade colour of each row of pixels will be set to {@code (b, b, b, a * m)} 
	 * where {@code b} is the brightness, {@code a} is the alpha value (this), and {@code m} is the modifier.
	 * <p>
	 * Note: These are the original shading values from the Targa texture Smooth_v2.
	 */
	private static int[] ALPHA_MAP = {
		73,
		152,
		154,
		156,
		158,
		160,
		162,
		164,
		166,
		167,
		168,
		169,
		170,
		171,
		172,
		173,
		174,
		175,
		176,
		177,
		178,
		179,
		180,
		181,
		181,
		182,
		182,
		183,
		183,
		184,
		184,
		221
	};
	
	private static int getAlpha(int pRow) {
		return (int)(ALPHA_MAP[pRow] * MODIFIER);
	}
	
	public static void applyTexture(Display pDisplay, Image pImage) {
		int height = pImage.getImageData().height;
		int width = pImage.getImageData().width;
		GC brush = new GC(pImage);

		brush.setAdvanced(true);
		brush.setForeground(new Color(pDisplay, BRIGHTNESS, BRIGHTNESS, BRIGHTNESS));
		// Set the alpha value
		brush.setAlpha(getAlpha(0));
		// Draw the top row
		brush.drawLine(0, 0, width - 1, 0);
		
		for (int i = 1; i < height - 1; i++) {
			brush.setAlpha(getAlpha((int)((double)ALPHA_MAP.length / height * i)));
			
			brush.drawLine(0, i, width, i);
		}
		
		brush.setAlpha(getAlpha(ALPHA_MAP.length - 1));
		
		brush.drawLine(0, height - 1, width, height - 1);
		
		brush.dispose();
	}
}